package com.domainlanguage.time;

import com.domainlanguage.time.Duration;
import org.hibernate.HibernateException;
import org.hibernate.type.ImmutableType;
import org.hibernate.usertype.UserType;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * Hibernate type for {@link com.domainlanguage.time.Duration}.
 *
 * Backed by {@link java.sql.Types.BIGINT}.
 *
 */
public class DurationType extends ImmutableType {

    @Override
    public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
        final long quantity = rs.getLong(name);
        return Duration.milliseconds(quantity);
    }

    @Override
    public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
        final Duration duration = (Duration) value;
        st.setLong(index, duration.inBaseUnits());
    }

    @Override
    public int sqlType() {
        return Types.BIGINT;
    }

    @Override
    public String toString(Object value) throws HibernateException {
        final Duration duration = (Duration) value;
        return String.valueOf(duration.inBaseUnits());
    }

    @Override
    public Object fromStringValue(String xml) throws HibernateException {
        return Duration.milliseconds(Long.parseLong(xml));
    }

    @Override
    public Class getReturnedClass() {
        return Duration.class;
    }

    @Override
    public String getName() {
        return "duration";
    }

}
